package com.derbysoft.lowcostadapter.dswitch3.handler.impl;

import com.derbysoft.dswitch.dto.common.KeyValue;
import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailResponse;
import com.derbysoft.lowcostadapter.commons.log.TransactionLogger;
import com.derbysoft.lowcostadapter.commons.model.OperationType;
import com.derbysoft.lowcostadapter.commons.model.TransactionLog;
import com.derbysoft.lowcostadapter.dswitch2.service.helper.Constant;
import com.derbysoft.lowcostadapter.dswitch3.handler.RemoteServiceHandler;
import com.derbysoft.lowcostadapter.dswitch3.service.HotelProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.Date;

/**
 * Created by: jason
 * Date: 2012-05-22
 */
@Service("hotelNoCachedAvailHandler")
public class HotelNoCachedAvailHandler extends AbstractDSwitch3Handler<HotelAvailRequest, HotelAvailResponse>
        implements RemoteServiceHandler<HotelAvailRequest, HotelAvailResponse> {

    @Autowired
    @Qualifier("ds3HotelCachedAvailService")
    protected HotelProviderService<HotelAvailRequest, HotelAvailResponse> ds3HotelCachedAvailService;

    @Autowired
    @Qualifier("ds3GetAvailService")
    protected HotelProviderService<HotelAvailRequest, HotelAvailResponse> ds3GetNoCachedAvailService;

    @Override
    public HotelAvailResponse handle(HotelAvailRequest request) {
        TransactionLogger.getAvailLogger().set(createTransactionLog(request));

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        HotelAvailResponse response = ds3GetNoCachedAvailService.execute(request);

        stopWatch.stop();
        long elapsedTime = stopWatch.getTotalTimeMillis();

        response.getElapsedTimes().add(new KeyValue(ElapsedTimeType.LCB_ADAPTER.name(), String.valueOf(elapsedTime)));
        TransactionLogger.getAvailLogger().get().setTimeSpan(elapsedTime);

        if (Boolean.valueOf(loadSystemVariable(Constant.APPEND_DERBY_LOG).getValue())) {
            appendLogDetail(request, response);
        }
        return response;
    }

    private TransactionLog createTransactionLog(HotelAvailRequest request) {
        TransactionLog transactionLog = new TransactionLog();
        transactionLog.setTaskId(request.getHeader().getTaskId());
        transactionLog.setChannel(request.getHeader().getSource());
        transactionLog.setOperationType(OperationType.HOTEL_AVAIL);
        transactionLog.setHotels(request.getHotelAvailRQ().getAvailCriteria().getHotelCodesList().get(0));
        transactionLog.setTimestamp(new Date());
        return transactionLog;
    }
}
